// import { AlipayCircleOutlined, TaobaoCircleOutlined, WeiboCircleOutlined } from '@ant-design/icons';
import { Alert, Checkbox, Radio, Modal, Button, InputNumber, Input, message } from 'antd';
import React, { useEffect, useState, useRef } from 'react';
import { connect, FormattedMessage, setLocale, getLocale } from 'umi';
import LoginForm from './components/Login';
import styles from './style.less';
import Cookies from 'js-cookie';

const { Tab, UserName, Password, Submit } = LoginForm;
const QRCode = require('qrcode.react');

const LoginMessage = ({ content }) => (
  <Alert
    style={{
      marginBottom: 24,
    }}
    message={content}
    type="error"
    showIcon
  />
);

const Login = (props) => {
  const { userLogin = {}, submitting } = props;
  const { status, type: loginType } = userLogin;
  const [autoLogin, setAutoLogin] = useState(true);
  const [type, setType] = useState('sQcode');
  const [qcVal, setQcVal] = useState('');
  const [sMtid, setSmtid] = useState(null);
  const [username, setUsername] = useState('');
  const [name, setName] = useState('');
  const [loginStatus, setLoginStatus] = useState(false);
  const [changeToSQcode, setChangeToSQcode] = useState(false);
  const [radioValue, setRadioValue] = React.useState(1);
  const [tokenModalShow, setTokenModalShow] = React.useState(false);
  const [num1, setNum1] = React.useState('');
  const [num2, setNum2] = React.useState('');
  const [num3, setNum3] = React.useState('');
  const [num4, setNum4] = React.useState('');
  const [num5, setNum5] = React.useState('');
  const [num6, setNum6] = React.useState('');

  const inputRefs = useRef();

  useEffect(() => {
    inputRefs.current = [];
  }, []);

  const handleSubmit = (values) => {
    const { dispatch } = props;
    // 令牌登陆
    if (radioValue === 2 && type === 'sQuick') {
      setTokenModalShow(true);
      inputRefs.current[1].focus();
      return;
    } else {
      setTokenModalShow(false);
    }
    // 推送登陆
    if (type === 'sQuick') {
      // eslint-disable-next-line no-use-before-define
      quickLogin();
    } else {
      // 账密登陆
      dispatch({
        type: 'login/login',
        payload: { ...values, type, sMtid },
      });
    }
  };

  const handleOk = () => {
    if (num1 === '' || num2 === '' || num3 === '' || num4 === '' || num5 === '' || num6 === '') {
      message.error(
        getLocale() === 'zh-CN' ? '必填项不可为空' : 'Compulsory fields must not be blank',
      );
      return;
    }
    let token = num1 + num2 + num3 + num4 + num5 + num6;
    quickToken(token);
    setTokenModalShow(false);
  };

  const handleCancel = () => {
    setTokenModalShow(false);
    setNum1('');
    setNum2('');
    setNum3('');
    setNum4('');
    setNum5('');
    setNum6('');
  };

  const onRadioChange = (e) => {
    /*console.log('radio checked', e.target.value);*/
    setRadioValue(e.target.value);
  };

  useEffect(() => {
    if (type === 'account') {
      clearInterval(sMtid);
      setSmtid(null);
    } else {
      clearInterval(sMtid);
      setSmtid(null);
      // eslint-disable-next-line no-use-before-define
      getQc();
    }
  }, [type]);

  function getQc() {
    const { dispatch } = props;
    const params = {
      // token: document.cookie.split(";")[0].split("=")[1],
      // eslint-disable-next-line no-use-before-define
      token: guid(),
    };
    dispatch({
      type: 'login/sMQcode',
      payload: params,
      callback: (res) => {
        let sTid;
        setQcVal(JSON.stringify(res));
        if (res && res.status === 200) {
          if (res.data.userName && changeToSQcode === false) {
            setUsername(res.data.userName);
            setName(res.data.userName.split('-')[0]);
            setLoginStatus(false);
            setType('sQuick');
            return;
          }
          setType('sQcode');
          const ct = {
            appId: res.data.appId,
            token: res.data.token,
            scenId: res.data.scenId,
            timestamp: new Date().getTime(),
          };
          setQcVal(JSON.stringify(ct));
          sTid = setInterval(() => {
            ct.timestamp = new Date().getTime();
            setQcVal(JSON.stringify(ct));
            // eslint-disable-next-line no-use-before-define
            queryToken(res.data.token, sTid);
          }, 3000);
          setSmtid(sTid);
          // eslint-disable-next-line consistent-return
          return () => {
            clearInterval(sTid);
            sTid = null;
          };
        }
      },
    });
  }

  function queryToken(token, stid) {
    const { dispatch } = props;
    const params = {
      token,
      sTid: stid,
    };
    dispatch({
      type: 'login/queryToken',
      payload: params,
    });
  }

  function changeToQCode() {
    setChangeToSQcode(true);
    setUsername('');
    setType('sQcode');
  }

  function quickLogin() {
    const { dispatch } = props;
    dispatch({
      type: 'login/quickLogin',
      payload: {},
      // eslint-disable-next-line consistent-return
      callback: (res) => {
        let sTid;
        if (res && res.status === 200) {
          // 是否展示dapp确认登录span
          setLoginStatus(true);
          let timesRun = 0;
          sTid = setInterval(() => {
            timesRun += 1;
            // 只循环100次
            if (timesRun === 100) {
              clearInterval(sTid);
              changeToQCode();
            } else {
              // eslint-disable-next-line no-use-before-define
              quickLoginCallBack(res.data.token, sTid);
            }
          }, 3000);
          setSmtid(sTid);
          return () => {
            clearInterval(sTid);
            sTid = null;
          };
        }
      },
    });
  }

  function quickLoginCallBack(token, stid) {
    const { dispatch } = props;
    const params = {
      token,
      sTid: stid,
      loginId: Cookies.get('loginId'),
    };
    dispatch({
      type: 'login/quickLoginCallBack',
      payload: params,
    });
  }

  function quickToken(dynamicToken) {
    const { dispatch } = props;
    const params = {
      dynamicToken: dynamicToken,
      username: name,
      loginId: Cookies.get('loginId'),
    };
    dispatch({
      type: 'login/quickToken',
      payload: params,
      callback: (res) => {
        if (res && res.status !== 200) {
          message.error(getLocale() === 'zh-CN' ? '令牌错误' : 'Token error');
          setTokenModalShow(true);
          setNum1('');
          setNum2('');
          setNum3('');
          setNum4('');
          setNum5('');
          setNum6('');
          inputRefs.current[1].focus();
        }
      },
    });
  }

  function onNum1Change(e) {
    setNum1(e.target.value);
    if (inputRefs.current[1]) {
      inputRefs.current[2].focus();
    } else {
      // inputRefs.current[index].blur()
    }
    /* actionRef2.focus();*/
  }
  function onNum2Change(e) {
    setNum2(e.target.value);
    if (inputRefs.current[2]) {
      inputRefs.current[3].focus();
    } else {
      // inputRefs.current[index].blur()
    }
    /*  inputRef3.current.focus({
      cursor: 'start',
    });*/
  }
  function onNum3Change(e) {
    setNum3(e.target.value);
    if (inputRefs.current[3]) {
      inputRefs.current[4].focus();
    } else {
      // inputRefs.current[index].blur()
    }
    /*inputRef4.current.focus({
      cursor: 'start',
    });*/
  }

  function onNum4Change(e) {
    setNum4(e.target.value);
    if (inputRefs.current[4]) {
      inputRefs.current[5].focus();
    } else {
      // inputRefs.current[index].blur()
    }
    /*inputRef5.current.focus({
      cursor: 'start',
    });*/
  }

  function onNum5Change(e) {
    setNum5(e.target.value);
    if (inputRefs.current[5]) {
      inputRefs.current[6].focus();
    } else {
      // inputRefs.current[index].blur()
    }
    /* inputRef6.current.focus({
      cursor: 'start',
    });*/
  }

  function onNum6Change(e) {
    setNum6(e.target.value);
  }

  function S4() {
    // eslint-disable-next-line no-bitwise
    return (((1 + Math.random()) * 0x10000) | 0).toString(16).substring(1);
  }

  function guid() {
    return `${S4() + S4()}-${S4()}-${S4()}-${S4()}-${S4()}${S4()}${S4()}`;
  }

  return (
    <div className={styles.main}>
      <LoginForm
        activeKey={type}
        onTabChange={setType}
        onSubmit={handleSubmit}
        className={styles.loginForm}
      >
        <Tab
          key={username ? 'sQuick' : 'sQcode'}
          tab={
            username ? (
              <FormattedMessage id="app.quick.login" defaultMessage="快捷登录" />
            ) : (
              <FormattedMessage id="app.scan.login" defaultMessage="扫码登录" />
            )
          }
        >
          {/* {status !== 200 && loginType === 'sQcode' && !submitting && ( */}
          {/*  <LoginMessage content="扫码认证失败"/> */}
          {/* )} */}
          <div style={{ display: type === 'sQcode' ? '' : 'none' }}>
            <div className={styles.qrCodeDiv}>
              <QRCode value={qcVal.toString()} size={140} id="qrcode" />
            </div>
            <p className={styles.qcCodeTxt}>
              <FormattedMessage
                id="app.account.dapp.scan"
                defaultMessage="请使用通付盾DApp扫码登录"
              />
            </p>
          </div>

          <div style={{ display: type === 'sQuick' ? '' : 'none' }}>
            <div className={styles.quickCodeStyle}>
              <span role="img" aria-label="user" className={styles.quickImg}>
                <svg
                  viewBox="64 64 896 896"
                  focusable="false"
                  className=""
                  data-icon="user"
                  style={{ width: '1em', height: '1em' }}
                  fill="currentColor"
                  aria-hidden="true"
                >
                  <path d="M858.5 763.6a374 374 0 00-80.6-119.5 375.63 375.63 0 00-119.5-80.6c-.4-.2-.8-.3-1.2-.5C719.5 518 760 444.7 760 362c0-137-111-248-248-248S264 225 264 362c0 82.7 40.5 156 102.8 201.1-.4.2-.8.3-1.2.5-44.8 18.9-85 46-119.5 80.6a375.63 375.63 0 00-80.6 119.5A371.7 371.7 0 00136 901.8a8 8 0 008 8.2h60c4.4 0 7.9-3.5 8-7.8 2-77.2 33-149.5 87.8-204.3 56.7-56.7 132-87.9 212.2-87.9s155.5 31.2 212.2 87.9C779 752.7 810 825 812 902.2c.1 4.4 3.6 7.8 8 7.8h60a8 8 0 008-8.2c-1-47.8-10.9-94.3-29.5-138.2zM512 534c-45.9 0-89.1-17.9-121.6-50.4S340 407.9 340 362c0-45.9 17.9-89.1 50.4-121.6S466.1 190 512 190s89.1 17.9 121.6 50.4S684 316.1 684 362c0 45.9-17.9 89.1-50.4 121.6S557.9 534 512 534z"></path>
                </svg>
              </span>
            </div>
            <div style={{ textAlign: 'center', fontSize: '16px' }}>{username}</div>
            <div style={{ marginLeft: '77px', marginTop: '10px' }}>
              <Radio.Group onChange={onRadioChange} value={radioValue}>
                <Radio value={1}>
                  <FormattedMessage id="app.push.login" defaultMessage="推送登录" />
                </Radio>
                <Radio value={2}>
                  <FormattedMessage id="app.token.login" defaultMessage="令牌登录" />
                </Radio>
              </Radio.Group>
            </div>

            <div style={{ display: loginStatus === false ? '' : 'none' }}>
              <Submit loading={submitting}>
                <FormattedMessage id="app.immediately.login" defaultMessage="立即登录" />
              </Submit>
              <div className={styles.changeAccount} onClick={changeToQCode}>
                <span>
                  <FormattedMessage id="app.account.check" defaultMessage="切换账号" />
                </span>
              </div>
            </div>
            <div style={{ display: loginStatus === true ? '' : 'none' }}>
              <div id="afterQuickLogin" style={{ display: 'block' }}>
                <div style={{ display: 'flex', justifyContent: 'center', marginTop: '20px' }}>
                  <div style={{ color: '#bebebf', textAlign: 'center' }}>
                    <span style={{ fontSize: '13px' }}>
                      <FormattedMessage
                        id="app.account.dapp.token.confirm"
                        defaultMessage="请在通付盾Dapp上确认登录"
                      />
                    </span>
                  </div>
                </div>
                <div className={styles.downLoadStyle}>
                  <i className={styles.downLoadBox}>
                    <FormattedMessage id="app.download" defaultMessage="立即下载" />
                  </i>
                  <em className={styles.downLoadKeyCoin}>
                    <img style={{ border: 'none' }} width="100%" src="../../../../downLoad.png" />
                  </em>
                </div>
              </div>
            </div>
          </div>
        </Tab>

        <Tab key="account" tab={<FormattedMessage id="app.pwd.login" defaultMessage="账密登录" />}>
          {status === 500 && loginType === 'account' && !submitting && (
            <LoginMessage
              content={
                <FormattedMessage id="app.account.error" defaultMessage="账户或密码错误！" />
              }
            />
          )}

          <UserName
            name="userName"
            placeholder={getLocale() === 'zh-CN' ? '邮箱名称' : 'Email Address'}
            rules={[
              {
                required: true,
                message: (
                  <FormattedMessage
                    id="app.account.mail.name.prompt"
                    defaultMessage="请输入邮箱名称!"
                  />
                ),
              },
            ]}
          />
          <Password
            name="password"
            placeholder={getLocale() === 'zh-CN' ? '邮箱密码' : 'Email Password'}
            rules={[
              {
                required: true,
                message: (
                  <FormattedMessage
                    id="app.account.mail.pwd.prompt"
                    defaultMessage="请输入邮箱密码！"
                  />
                ),
              },
            ]}
          />
          <div>
            <Checkbox checked={autoLogin} onChange={(e) => setAutoLogin(e.target.checked)}>
              <FormattedMessage id="app.auto.login" defaultMessage="自动登录" />
            </Checkbox>
            {/*  <a
              style={{
                float: 'right',
              }}
            >
              忘记密码
            </a>*/}
          </div>
          <Submit loading={submitting}>
            <FormattedMessage id="app.immediately.login" defaultMessage="立即登录" />
          </Submit>
        </Tab>
      </LoginForm>
      {tokenModalShow ? (
        <Modal
          title={
            <FormattedMessage
              id="app.account.dapp.token"
              defaultMessage="请输入通付盾DApp中的动态令牌"
            />
          }
          visible={tokenModalShow}
          onOk={handleOk}
          onCancel={handleCancel}
          width={'388px'}
          style={{ marginTop: '5%' }}
        >
          <Input
            ref={(input) => (inputRefs.current[1] = input)}
            maxLength={1}
            onChange={onNum1Change}
            style={{ width: '40px', height: '36px', marginLeft: '23px' }}
          />
          <Input
            ref={(input) => (inputRefs.current[2] = input)}
            maxLength={1}
            onChange={onNum2Change}
            style={{ width: '40px', height: '36px', marginLeft: '10px' }}
          />
          <Input
            ref={(input) => (inputRefs.current[3] = input)}
            maxLength={1}
            onChange={onNum3Change}
            style={{ width: '40px', height: '36px', marginLeft: '10px' }}
          />
          <Input
            ref={(input) => (inputRefs.current[4] = input)}
            maxLength={1}
            onChange={onNum4Change}
            style={{ width: '40px', height: '36px', marginLeft: '10px' }}
          />
          <Input
            ref={(input) => (inputRefs.current[5] = input)}
            maxLength={1}
            onChange={onNum5Change}
            style={{ width: '40px', height: '36px', marginLeft: '10px' }}
          />
          <Input
            ref={(input) => (inputRefs.current[6] = input)}
            maxLength={1}
            onChange={onNum6Change}
            style={{ width: '40px', height: '36px', marginLeft: '10px' }}
          />
        </Modal>
      ) : (
        ''
      )}
    </div>
  );
};

export default connect(({ login, loading }) => ({
  userLogin: login,
  submitting: loading.effects['login/login'],
}))(Login);
